package com.zhonggong.empConsumer.service.impl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.util.ByteSequence;

import com.zhonggong.empConsumer.dao.ConsumerDao;
import com.zhonggong.empConsumer.dao.impl.ConsumerDaoImpl;
import com.zhonggong.empConsumer.service.ConsumerManager;
import com.zhonggong.network.emp.model.Emp;

public class ConsumerManagerImpl implements ConsumerManager {
	public List<Emp> empList = new ArrayList<Emp>();
	public ConsumerDao consumerDao = new ConsumerDaoImpl();

	public void receive() {
		Consumer c = new Consumer();
		ConnectionFactory factory = new ActiveMQConnectionFactory(c.url);
		Connection connection;
		try {
			connection = factory.createConnection();
			connection.start();
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(c.queueName);
			MessageConsumer consumer = session.createConsumer(destination);
			consumer.setMessageListener(new MessageListener() {
				public void onMessage(Message arg) {
					BytesMessage bm = (BytesMessage) arg;
					Field field = null;
					Class<?> clazz = bm.getClass();
					for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
						try {
							field = clazz.getDeclaredField("content");
						} catch (Exception e) {
						}
					}
					field.setAccessible(true);
					byte[] by = null;
					try {
						ByteSequence b = (ByteSequence) field.get(bm);
						by = b.getData();
					} catch (IllegalArgumentException e1) {
						e1.printStackTrace();
					} catch (IllegalAccessException e1) {
						e1.printStackTrace();
					}
					UnserializeForList uf = new UnserializeForList();
					List<Emp> empList = uf.unserializeForList(by); // 实现反序列化
					System.out.println(empList);
					Iterator<Emp> iterator = empList.iterator();
					while (iterator.hasNext()) {
						Emp emp = new Emp();
						emp = iterator.next();
						consumerDao.add(emp);
					}
				}
			});
		} catch (JMSException e2) {
			e2.printStackTrace();
		}
	}
	
	public void writefile(String filename,String text) {
		consumerDao.writefile(filename, text);
	}
}
